package com.tsunami.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * easyPoi excel导出工具类
 *
 * @author lx
 * @date 2024/4/12 11:46
 */
@Slf4j
public class EasyExcelExportUtil {
    private EasyExcelExportUtil() {
    }

    /**
     * 允许导出的最大条数
     */
    private static final Integer EXPORT_EXCEL_MAX_NUM = 10000;

    /**
     * 获取导出的Workbook对象
     *
     * @param title     大标题
     * @param sheetName sheet名称
     * @param object    导出实体
     * @param list      数据集合
     * @return 生成工作表
     */
    public static Workbook getWorkbook(String title, String sheetName, Class<?> object, List<?> list) {
        //判断导出数据是否是空
        if (list == null) {
            list = new ArrayList<>();
        }
        if (list.size() > EXPORT_EXCEL_MAX_NUM) {
            title = "导出数据行数超过" + EXPORT_EXCEL_MAX_NUM + "条，无法导出；请添加导出条件";
            list = new ArrayList<>();
        }
        //获取导出参数
        ExportParams exportParams = new ExportParams();
        exportParams.setStyle(EasyExcelStyleUtil.class);
        exportParams.setHeight((short) 6);
        exportParams.setTitle(title);

        return ExcelExportUtil.exportExcel(exportParams, object, list);
    }

    /**
     * 获取导出的Workbook对象
     *
     * @param path 模板路径
     * @param map  导出内容map
     * @return 生成工作表
     */
    public static Workbook getWorkbook(String path, Map<String, Object> map) {

        TemplateExportParams params = new TemplateExportParams();
        //设置样式
        params.setStyle(EasyExcelStyleUtil.class);
        return ExcelExportUtil.exportExcel(params, map);
    }

    /**
     * 导出Excel
     *
     * @param workbook workbook流
     * @param fileName 文件名
     * @param response 响应
     */
    public static void exportExcel(Workbook workbook, String fileName, HttpServletResponse response) {

        try (OutputStream out = response.getOutputStream()) {
            String name = URLEncoder.encode(fileName, "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件导出异常，详情如下：", e);
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                log.error("文件导出异常，详情如下：", e);
            }
        }
    }
}
